package com.heye.imheye.controller;

import com.heye.imheye.dto.MessageSendReq;
import com.heye.imheye.dto.UserInfo;
import com.heye.imheye.entity.Message;
import com.heye.imheye.event.EventPublisher;
import com.heye.imheye.repository.MessageRepository;
import com.heye.imheye.util.ContextUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/message")
@RequiredArgsConstructor
public class MessageController {

    private final EventPublisher eventPublisher;
    private final MessageRepository messageRepository;

    @PostMapping("/send")
    public void send(@RequestBody MessageSendReq req) {
        UserInfo userInfo = ContextUtil.getUserInfo();
        Message message = new Message();
        message.setFormId(userInfo.id());
        message.setToId(req.toId());
        message.setToType(req.toType());
        message.setType(req.type());
        message.setContent(req.content());
        messageRepository.save(message);

        eventPublisher.publish(message);
    }
}
